package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *  1、公钥和私钥为了生成token： jwt
 *  2、$2a$10$Xw9OGi5vK8FESKJRscHAtu4T2a02CYpdY3Msg2bpq4gZNHSoOXfPi： 跟公钥和私钥没有关系，它是用BCrypt算法生成
 */
@Slf4j
@Component
public class PrivilegeInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties prop;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 获取请求头中的token
            String token = request.getHeader(prop.getApp().getHeaderName());
            // 解析token
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
            // 校验token
            AppInfo app = payload.getUserInfo();
            // 获取当前微服务的id： 用户微服务自己的id
            Long currentServiceId = prop.getApp().getId();
            // 取出token中的targetList
            List<Long> targetList = app.getTargetList();
            // 判断当前服务的id有没有存在 app的targetList中
            if(targetList==null || !targetList.contains(currentServiceId)){
                //抛异常
                log.error("没有访问权限");
                throw new RuntimeException("没有访问权限");
            }
            // 正常访问
            log.info("【用户微服务】服务{}，正在访问资源：{}", app.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【用户微服务】拒绝服务访问，app的token认证失败！");
            return false;
        }
    }
}
